<template>
  <div class="viewContain">
    <el-form ref="form" :model="form" label-width="">
      <el-form-item label="请选择发货地：">
        <el-select v-model="areaId" filterable clearable placeholder="请选择" size="mini" style="width: 215px">
          <el-option
            v-for="item1 in areaList"
            :key="item1.value"
            :label="item1.label"
            :value="item1.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="请选择发货地：">
        <el-radio-group v-model="deliverInfo.radio" size="small">
          <el-radio v-for="item in areaList" :key="item.id" style="margin-bottom:10px" :label="item.id" border>{{ item.name }}</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <div v-for="(item, index) in selectGoodsList" :key="index" class="list">
        <el-row>
          <el-col :xs="{ span: 24 }" :sm="{ span: 8 }" :md="{ span: 8 }" :xl="{ span: 8 }">
            <el-form-item :label="'发货物品' + (index+1) + ':'" size="mini">
              <el-select
                v-model="item.id"
                size="mini"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词"
                :remote-method="remoteMethod"
                :loading="loadingGoods"
                @change="changeGoods"
              >
                <el-option
                  v-for="item1 in options"
                  :key="item1.value"
                  :label="item1.label"
                  :value="item1.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="{ span: 24 }" :sm="{ span: 4 }" :md="{ span: 4 }" :xl="{ span: 4 }">
            <el-input-number v-model="item.num" size="mini" :min="1" :max="10" label="描述文字" :step-strictly="true" @change="handleChange" />
          </el-col>
          <!-- <el-col :xs="{ span: 24 }" :sm="{ span: 4 }" :md="{ span: 4 }" :xl="{ span: 4 }">
            <el-button type="danger" size="mini" @click="deleteItem(index)">删除</el-button>
          </el-col> -->
        </el-row>
        <div class="operate" style="margin-bottom: 10px">
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="addGoods">新增商品</el-button>
          <el-button type="primary" size="mini" icon="el-icon-refrigerator" @click="startCalculate">开始计算</el-button>
          <el-button type="danger" size="mini" icon="el-icon-refrigerator" @click="deleteItem(index)">删除</el-button>
        </div>
      </div>
    </el-form>
    <!-- <el-form-item label="请输入发货重量（单位: kg）：">
        <el-input v-model="deliverInfo.inputWeight" style="width: 300px;" oninput="value=value.replace(/[^0-9.]/g,'')" placeholder="请输入重量(单位: kg)" clearable />
      </el-form-item> -->
    <!-- <el-button type="primary" @click="isCommonTiket">点击计算</el-button> -->
    <!-- <el-form-item v-if="isShow" label="计算结果：">
        <div class="result">
          <span v-for="item in selectData" :key="item.id" class="item">
            <span>{{ item.deliveryName }} : {{ item.price }}元</span>
          </span>
          <div class="recomend">系统推荐:
            <span>{{ recomendRes.deliveryName }}</span>
          </div>
        </div>
      </el-form-item> -->
    <div v-if="isShow" v-loading="calLoading" class="resultBox">
      <div class="result">
        <span v-for="item in selectData" :key="item.id" class="item">
          <span>{{ item.deliveryName }} : {{ item.price }}元</span>
        </span>
        <div class="recomend">系统推荐:
          <span>{{ recomendRes.deliveryName }}</span>
        </div>
      </div>
    </div>
    <!-- <div v-else v-loading="calLoading" class="resultBox">
      <div class="result">
        计算中...
      </div>
    </div> -->
  </div>
</template>

<script>
import { getDeliveryPrice, provinceList, goodsList } from '@/api/index'

export default {
  data() {
    return {
      calLoading: false,
      areaId: '',
      address: [],
      loadingGoods: false,
      form: {},
      num: 0,
      listQuery: {
        // pageNum: 1,
        // pageSize: 9999
        goodsName: ''

      },
      listQuery_goods: {
        pageNum: 1,
        pageSize: 9999,
        goodsName: ''
      },
      goodsList: [], // 商品列表-接口返回
      goodsLists: [], // 商品列表-下拉
      areaList: [],
      deliverInfo: {
        radio: '',
        inputWeight: ''
      },
      tableData: [],
      priceList: [],
      selectData: [],
      isShow: false,
      recomendRes: {},
      commonPrice: '', // 通票价格
      goodsName: '',
      options: [],
      selectGoodsList: [
        {
          id: '',
          num: 0
        }
      ]
    }
  },
  watch: {

  },
  mounted() {
    this.getList()
    this.getAddressList()
    this.getGoodsList()
  },
  methods: {
    remoteMethod(query) {
      if (query !== '') {
        this.loadingGoods = true
        setTimeout(() => {
          this.loadingGoods = false
          this.options = this.goodsLists.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1
          });
        }, 200)
      } else {
        this.options = []
      }
    },
    changeGoods(val) {
      // console.log('选中值的变化===', val)
      // console.log('this.goodsList===', this.goodsList)
      this.weigth = this.goodsList.filter(item => item.id === val)[0].goodsWeight
      // console.log('this.weigth===', this.weigth)
    },
    handleChange(val) {},
    // 新增商品
    addGoods() {
      this.selectGoodsList.push({
        id: '',
        num: 0
      })
    },
    deleteItem(index) {
      // this.$confirm('确定要删除该条商品吗?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   this.selectGoodsList.splice(index, 1)
      // })
      if (this.selectGoodsList.length === 1) {
        this.$message({
          type: 'warning',
          message: '请至少保留一个商品!'
        })
        return
      }
      this.selectGoodsList.splice(index, 1)
    },
    getGoodsList() {
      goodsList(this.listQuery_goods).then(res => {
        if (res.code === 200) {
          // const arr = []
          this.goodsList = res.data.list
          res.data.list.forEach(item => {
            this.goodsLists.push({ value: item.id, label: item.goodsName })
          })
          // console.log('this.goodsLists===', this.goodsLists)
        }
      })
    },
    startCalculate() {
      // console.log('this.selectGoodsList===', this.selectGoodsList)
      if (!this.areaId) {
        alert('请选择发货地!')
        return
      }
      this.selectGoodsList.forEach((item, index) => {
        if (!item.id) {
          alert(`请选择发货物品${index + 1}`)
          return
        }
      })
      const hasEveryId = this.selectGoodsList.every((item) => item.id !== '')
      if (hasEveryId) { this._isCommonTiket() }
    },
    // 根据总重量来计算
    _isCommonTiket() {
      this.calLoading = true
      this.isShow = false
      // 计算每行商品的总重量
      const singleGoodsWeight = []
      this.selectGoodsList.forEach(item => {
        console.log('item===', item)
        this.goodsList.forEach(item1 => {
          if (item.id === item1.id) {
            console.log('item1===', item1)
            singleGoodsWeight.push(item1.goodsWeight * item.num)
          }
        })
      })
      console.log('singleGoodsWeight===', singleGoodsWeight)
      // 计算总重量
      const totalWeight = singleGoodsWeight.reduce((x, y) => { return x + y })
      console.log('totalWeight===', totalWeight)
      console.log(this.tableData)
      const selectData = this.tableData.filter(item2 => item2.areaCode === this.areaId)
      console.log('selectData===', selectData)
      this.selectData = selectData
      const priceList = []
      // 计算单个省份对应的快递发货费用  续重*重量+3.5 =价格 // 3.5就是首重（面单价格）
      selectData.forEach(item3 => {
        item3.price = item3.secondWeight * totalWeight + item3.firstWeight
        item3.price = Number(item3.price.toFixed(2))
        priceList.push(item3.price)
      })
      console.log('priceList===', priceList)
      // 筛选出最便宜的价格
      var min = priceList[0]
      for (var i = 1; i < priceList.length; i++) {
        min = min < priceList[i] ? min : priceList[i]
      }

      // 找出最便宜的快递信息
      const recomend = selectData.filter(item => item.price === min)[0]
      this.recomendRes = recomend
      console.log('this.recomendRes===', this.recomendRes)
      setTimeout(() => { this.isShow = true }, 500)
      // this.isShow = true
      this.calLoading = false
    },
    // 根据数量来计算
    _isCommonTiket1() {
      // 先计算每个快递发货的成本
      const selectData = this.tableData.filter(item => item.areaCode === this.areaId)
      this.selectData = selectData
      console.log('selectData===', selectData)
      selectData.forEach(item1 => {
        this.selectGoodsList.forEach(item2 => {
          console.log('item2选的商品===', item2)
        })
      })

      // this.calLoading = true
      // this.isShow = false
      // // 计算每行商品的总重量
      // const singleGoodsWeight = []
      // const singleGoodsNums = []
      // const priceList = []
      // console.log('this.selectGoodsList===', this.selectGoodsList)
      this.selectGoodsList.forEach(item => {
        // console.log('item===', item)
        // const obj = this.goodsList.find(item1 => item1.id === item.id)
        // console.log(obj)
        // singleGoodsWeight.push(obj.goodsWeight)
        // singleGoodsNums.push(item.num)
        // selectData.forEach(item3 => {
        //   item3.price = (item3.secondWeight * obj.goodsWeight + item3.firstWeight)
        //   item3.price = Number(item3.price.toFixed(2))
        //   priceList.push(item3.price)
        // })
        // singleGoodsNums.push(item.num)
        // this.goodsList.forEach(item1 => {
        //   if (item.id === item1.id) {
        //     console.log('item1===', item1)
        //     // singleGoodsWeight.push(item1.goodsWeight)
        //     selectData.forEach(item3 => {
        //       item3.price = (item3.secondWeight * item1.goodsWeight + item3.firstWeight) * item.num
        //       item3.price = Number(item3.price.toFixed(2))
        //       priceList.push(item3.price)
        //     })
        //   }
        // })
      })

      // console.log('singleGoodsWeight===', singleGoodsWeight)
      // console.log('singleGoodsNums===', singleGoodsNums)

      selectData.forEach(item3 => {
        // console.log('item3===', item3)
        // singleGoodsWeight.forEach(item4 => {
        //   item3.price = (item3.secondWeight * item4 + item3.firstWeight)
        //   item3.price = Number(item3.price.toFixed(2))
        //   priceList.push(item3.price)
        // })
      })
      // console.log('priceList===', priceList)

      // 计算总重量
      // const totalWeight = singleGoodsWeight.reduce((x, y) => { return x + y })
      // console.log('totalWeight===', totalWeight)
      // console.log(this.tableData)
      // 计算单个省份对应的快递发货费用  续重*重量+3.5 =价格 // 3.5就是首重（面单价格）

      // 筛选出最便宜的价格
      // var min = priceList[0]
      // for (var i = 1; i < priceList.length; i++) {
      //   min = min < priceList[i] ? min : priceList[i]
      // }

      // // 找出最便宜的快递信息
      // const recomend = selectData.filter(item => item.price === min)[0]
      // this.recomendRes = recomend
      // console.log('this.recomendRes===', this.recomendRes)
      // setTimeout(() => { this.isShow = true }, 500)
      // // this.isShow = true
      // this.calLoading = false
    },
    /**
     *  计抛计算
     * （长cm*宽cm*高cm）/10000
     *  eg: 一台BF501重量为15kg 计抛折算为（50*50*100）/10000 = 25   25>15  所以出货重量按照25kg来计算
     */
    /**
     * 通票判断
     * 这里分为圆通和韵达
     */
    isCommonTiket(item1) {
      console.log('走通票===')
      const type = '' // 快递类型
      // 获取物体的重量
      const weigth = item1.weigth
      // 参考变量为3kg. 小于3就是走通票。
      const referenceValue = 3
      // 通票判断
      if (weigth <= referenceValue) {
        // 物体实际重量小于参考变量3，走通票
        if (type === 'YT') {
          console.log('圆通通票===')
          this.commonPrice = 3 // 新疆/西藏单独计算
        } else if (type === 'YD') {
          console.log('韵达通票===')
          if (weigth > 0 && weigth <= 0.5) {
            this.commonPrice = 2.55
          } else if (weigth > 0.5 && weigth <= 1) {
            this.commonPrice = 3.25
          } else if (weigth > 1 && weigth <= 2) {
            this.commonPrice = 4.45
          } else if (weigth > 2 && weigth <= 3) {
            this.commonPrice = 5.95
          }
        }
      } else {
        // 物体实际重量大于参考变量3，不走通票
        console.log('不走通票===')
        this._getResult()
      }
    },
    // 计抛判断
    beforeCalculate() {
      // 商品参数: 长度，宽度，高度，型号，名称
      const singleObject = {
        // length: 50, // 长(cm)
        // width: 50, // 宽(cm)
        // height: 100, // 高(cm)
        // weigth: 15 // 重量(kg)
        length: 50, // 长(cm)
        width: 50, // 宽(cm)
        height: 100, // 高(cm)
        weigth: 15 // 重量(kg)
      }
      var { length, width, height, weigth } = singleObject
      // 计算体积
      const volume = length * width * height
      if ((volume / 10000) > weigth) {
        weigth = volume / 10000
      }
      return weigth
    },
    _getResult() {

    },

    getResult() {
      console.log('this.beforeCalculate()===', this.beforeCalculate())
      const weigth = this.beforeCalculate()
      // console.log(this.deliverInfo.inputWeight)
      // 找出发货地id和物体重量
      // const { inputWeight, radio } = this.deliverInfo
      // console.log('inputWeight===', inputWeight)
      // console.log('radio===', radio)
      // if (!radio) {
      //   this.$message({
      //     type: 'warning',
      //     message: '请勾选发货地区!'
      //   })
      //   return
      // }
      // 找出对应省份的快递计费数据
      console.log(this.tableData)
      const selectData = this.tableData.filter(item => item.areaCode === this.areaId)
      const priceList = []
      console.log('selectData===', selectData)
      if (!selectData.length) {
        this.$message({
          type: 'warning',
          message: '暂无该地区快递信息!'
        })
        this.isShow = false
        return
      }
      // 计算单个身份对应的快递发货费用  续重*重量+3.5 =价格 // 3.5就是首重（面单价格）
      selectData.forEach(item => {
        item.price = item.secondWeight * weigth + item.firstWeight
        item.price = Number(item.price.toFixed(2))
        priceList.push(item.price)
      })
      console.log('priceList===', priceList)

      // 非空校验
      if (this.areaId) {
        this.isShow = true
        this.selectData = selectData
      } else {
        this.isShow = false
      }
      // 筛选出最便宜的价格
      var min = priceList[0]
      for (var i = 1; i < priceList.length; i++) {
        min = min < priceList[i] ? min : priceList[i]
      }

      // 找出最便宜的快递信息
      const recomend = selectData.filter(item => item.price === min)[0]
      this.recomendRes = recomend
    },
    getList() {
      this.loading = true
      getDeliveryPrice(this.listQuery).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.list
          this.loading = false
        } else {
          this.loading = false
        }
      })
    },
    getAddressList() {
      const params = { pageNum: 1, pageSize: 50 }
      provinceList(params).then(res => {
        // console.log('res===', res)
        if (res.code === 200) {
          const arr = []
          res.data.list.forEach(item => {
            arr.push({ value: item.id, label: item.name })
          })
          this.areaList = arr
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .viewContain {
    .list {
      border: 1px solid #ccc;
      padding: 20px;
      border-radius: 10px;
      margin-bottom: 10px;
    }
    .result {
      margin-top: 20px;
      .item {
        margin-right: 20px;
      }
      .recomend {
        span {
          color: red;
          font-size: 20px;
        }
      }
    }
    .resultBox {
      margin-top: 20px;
      border-radius: 10px;
      width: 1000px;
      height: 200px;
      border: 1px solid #ccc;
      .result {
        margin-top: 20px;
        .item {
          margin-right: 20px;
        }
        .recomend {
          margin-top: 20px;
          margin-left: 2px;
          span {
            color: red;
            font-size: 20px;
          }
        }
      }
    }
  }
</style>

